﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using Medianamik.Client.Data;
using Medianamik.Client.Data.Repositories;
using Medianamik.Client.MVP.Model.Service;
using Medianamik.Core;
using Medianamik.Core.Caching;
using Medianamik.Core.CodeGeneration;
using Medianamik.Core.Configuration;
using Medianamik.Core.DAL;
using Medianamik.Core.DAL.Repositories;
using Medianamik.Core.DAL.Services;
using Medianamik.Core.Logging;
using Medianamik.Core.Profile;
using Medianamik.Core.Urls;
using StructureMap;
using StructureMap.Configuration.DSL;
using CodeService = Medianamik.Core.CodeGeneration.CodeService;
using ConfigurationSectionName = Medianamik.Core.ConfigurationSectionName;
using Medianamik.Core.Sugar;

namespace MedianamikMagicScriptsRunner
{
    class Program
    {
        private static readonly MedianamikConfigSection Config = (MedianamikConfigSection)ConfigurationManager
                .GetSection(ConfigurationSectionName.MEDIANAMIK);

        public static readonly ILogger Logger = new Medianamik.Client.Utility().GetGlobalLogger();

        static bool _canceled;

        public static void Main(string[] args)
        {
            ObjectFactory.Initialize(container =>
            {
                container.AddRegistry<RepositoriesRegistry>();
            });
            AppDomainSetup test;

            var errors = 0;

            try
            {
                Console.CancelKeyPress += CancelRecyling;

                var cs = ConfigurationManager.ConnectionStrings["CS"];

                if (cs == null || String.IsNullOrEmpty(cs.ToString()))
                {
                    Console.WriteLine("Aucune connection string (CS) n'a été trouvée dans le fichier App.config");
                    errors++;
                }

                if (Config == null)
                {
                    Console.WriteLine(errors > 0 ? "\n" : "" +
                        "La section de configuration de Medianamik n'a pas été trouvée dans le fichier App.config");
                    errors++;
                }

                if (errors > 0)
                {
                    Console.Write("\nAppuyez sur une touche pour quitter...");
                    Console.ReadKey();
                }
                else
                {
                    Console.WriteLine("Configurations détectées : ");

                    var csProperties = cs.ToString().Split(new[] { ';' });
                    csProperties.ForEach(p => Console.WriteLine("\t- " + p.TrimStart(new[] { ' ' })));

                    var typesToExclude = new List<string>().ToArray();

                    var typesToExcludeConfig = ConfigurationManager.AppSettings["typesToExclude"];
                    if (typesToExcludeConfig != null)
                        typesToExclude = typesToExcludeConfig.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    var typesToInclude = new List<string>().ToArray();
                    var typesToIncludeConfig = ConfigurationManager.AppSettings["typesToInclude"];
                    if (typesToIncludeConfig != null)
                        typesToInclude = typesToIncludeConfig.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    var allTypes = NodeTypeManager.GetAllTypes(true)
                            .Where(t => typesToExclude.Length == 0 || !typesToExclude.Any(y => new Guid(y) == t.ID))
                            .Where(t => typesToInclude.Length == 0 || typesToInclude.Any(y => new Guid(y) == t.ID))
                            .Where(t => t.IsGenerated)
                            .OrderByDescending(t => t.Depth);

                    var allTypesCount = allTypes.Count();

                    Console.WriteLine("\nListe des types (" + allTypesCount + ") : ");

                    allTypes.ForEach(t => Console.WriteLine("\t- " + t.Name));

                    var answer = "";
                    while (answer == "")
                    {
                        answer = DisplayOperations();

                        switch (answer)
                        {
                            case "1":
                                answer = ConfirmAction("Êtes-vous certain de vouloir recycler les tables générées ? (O/N) : ",
                                    () => RecycleGeneratedTables(allTypes, allTypesCount));
                                break;
                            case "2":
                                answer = ConfirmAction("Êtes-vous certain de vouloir générer la DAL ? (O/N) : ",
                                    GenerateDALClientCode);
                                break;
                            case "3":
                                answer = ConfirmAction("Êtes-vous certain de vouloir nettoyer la BD ? (O/N) : ",
                                    CleanDatabase);
                                break;
                            case "4":
                                answer = ConfirmAction("Êtes-vous certain de vouloir appliquer les mises-à-jour ? (O/N) : ",
                                    UpdateMedianamik);
                                break;
                            case "5":
                                answer = ConfirmAction("Êtes-vous certain de vouloir générer la classe MyProfile? (O/N) : ",
                                    GenerateMyProfile);
                                break;
                            case "6":
                                answer = ConfirmAction("ATTENTION : Vous vous apprêtez à désérialiser selon la classe MyProfile suivante : " +
                                    GetMyProfileClassPath() + "\nAssurez-vous d'avoir déposé le dll contenant la classe en question dans le même répertoire que cet exécutable." +
                                    "\nÊtes-vous certain de vouloir désérialiser les noeuds de type MedianamikProfile ? (O/N) : ",
                                    DeserializeProfileNodes);
                                break;
                            case "7":
                                answer = ConfirmAction("ATTENTION 1 : Assurez-vous d'avoir désérialisés les noeuds de types MedianamiProfile avant d'exécuter cette tâche." +
                                    "\nATTENTION 2 : Ne pas oublier de copier la classe UserProfile générée dans le répertoire Data de votre projet." +
                                    "\nÊtes-vous certain de vouloir installer le module de gestion des membres 2 ? (O/N) : ",
                                    InstallUserManagementModule2);
                                break;
                            case "8":
                                answer = ConfirmAction("Êtes-vous certain de vouloir générer la classe UserProfile ? (O/N) : ",
                                    GenerateUserProfile);
                                break;
                            case "9":
                                answer = ConfirmAction("Êtes-vous certain de vouloir passer à la version 2.3.1.x ou plus ? (O/N) : ",
                                    ConvertNodePropertyValuesToNodeRevision);
                                break;
                            case "10":
                                answer = ConfirmAction("Êtes-vous certain de vouloir passer à la version 2.4.x.x ou plus ? (O/N) : ",
                                    ConvertNodeRevisionToNewNodeRevision);
                                break;
                            case "11":
                                answer = ConfirmAction("Êtes-vous certain de vouloir ConvertNodeRevisionAllInOneToNodeRevisionWithCulture ? (O/N) : ",
                                    ConvertNodeRevisionAllInOneToNodeRevisionWithCulture);
                                break;
                            case "12":
                                answer = ConfirmAction("Êtes-vous certain de vouloir comparer ce site à un autre ? (O/N) : ",
                                    CompareSite);
                                break;
                            case "13":
                                answer = ConfirmAction("Êtes-vous certain de vouloir regénérer la vue User Profile ? (O/N) : ",
                                    RegenerateUserProfileView);
                                break;
                            case "14":
                                Console.Write("\n\nÊtes-vous certain de vouloir quitter ? (O/N) : ");

                                answer = Console.ReadKey().KeyChar.ToString();

                                if (!answer.Equals("o", StringComparison.OrdinalIgnoreCase))
                                {
                                    answer = "";
                                }

                                break;
                            default:
                                Console.Write("\n\nL'opération spécifiée n'est pas disponible...\n");
                                answer = "";
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write("\nUne erreur est survenue : " + ex + "\nAppuyez sur une touche pour quitter...");
                Console.ReadKey();
            }
        }

        private static void CompareSite()
        {
            var urls = new ObjectFactory<IUrlDictionary>().Get();
            var domains = urls.GetDomains();

            for (var index = 0; index < domains.Count; index++)
            {
                var domain = domains[index];
                Console.WriteLine((index == 0 ? "\n" : "") + "\t- " + domain);
            }

            Console.Write("\n\t- Premier domaine : ");
            var firstDomain = Console.ReadLine();

            if (urls.GetDomains().Any(d => d.EqualsIgnoreCase(firstDomain)))
            {
                Console.Write("\n\t- Deuxième domaine : ");
                var secondDomain = Console.ReadLine();

                if (urls.GetDomains().Any(d => d.EqualsIgnoreCase(secondDomain)))
                {
                    Console.WriteLine("\n\t- Comparaison en cours... ");

                    var allEntries = urls.GetAllEntries();

                    var firstDomainUrls = allEntries.Where(u =>
                         firstDomain.EqualsIgnoreCase(u.Domain)).ToList();

                    var secondDomainUrls = allEntries.Where(u =>
                         secondDomain.EqualsIgnoreCase(u.Domain)).ToList();

                    Console.WriteLine("\n\t- Premier domaine : " + firstDomainUrls.Count);
                    Console.WriteLine("\t- Deuxième domaine : " + secondDomainUrls.Count);

                    if (firstDomainUrls.Count == secondDomainUrls.Count)
                    {
                        bool diff;

                        for (var index = 0; index < firstDomainUrls.Count; index++)
                        {
                            Logger.Warn("(" + (index + 1) + "/" + firstDomainUrls.Count + ")");

                            var firstDomainUrl = firstDomainUrls[index];
                            var relativeUrl = firstDomainUrl.RequestedPath;
                            //Console.WriteLine("\t- Url en cours : " + relativeUrl);
                            var firstDomainPage = GetPageResponseString(firstDomain, relativeUrl);
                            var secondDomainPage = GetPageResponseString(secondDomain, relativeUrl);
                            diff = !firstDomainPage.Equals(secondDomainPage);

                            if (diff)
                            {
                                //Console.WriteLine("\t- Url ayant des différences : " + relativeUrl);
                                Logger.Fatal("Url ayant des différences : " + relativeUrl);
                            }

                            if (_canceled)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("\t- Le nombre d'urls des deux domaines ne concorde pas.");
                    }
                }
                else
                {
                    Console.WriteLine("\t- Le deuxième domaine n'existe pas.");
                }
            }
            else
            {
                Console.WriteLine("\t- Le premier domaine n'existe pas.");
            }
        }

        public static string GetPageResponseString(string domain, string relativeUrl)
        {
            string result;
            var url = "http://" + domain + relativeUrl;

            try
            {
                using (var wc = new WebClient())
                {
                    result = wc.DownloadString(url);
                }

                //Remove domain
                result = Regex.Replace(result, domain, "");

                //Remove comments
                result = Regex.Replace(result, "<!--.*?-->", String.Empty, RegexOptions.Singleline);

                //Remove viewstate et autres du genre
                result = Regex.Replace(result, "<input[^>]*id=\"(__VIEWSTATE|__EVENTTARGET|__EVENTARGUMENT|__EVENTVALIDATION)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase);

                //HTML Decode
                result = HttpUtility.HtmlDecode(result);

                //result = RemoveWhitespace(result);
            }
            catch (WebException ex)
            {
                var response = (HttpWebResponse)ex.Response;

                switch (response.StatusCode)
                {
                    case HttpStatusCode.NotFound: // 404
                        Logger.Fatal("404 : " + url);
                        result = "404";
                        break;

                    case HttpStatusCode.InternalServerError: // 500
                        Logger.Fatal("500 : " + url);
                        result = "500";
                        break;

                    default:
                        throw;
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal("Exception : " + url + ex.ToStringWithDetails());
                result = "Exception";
            }

            return result;
        }

        private static string RemoveWhitespace(string input)
        {
            if (string.IsNullOrEmpty(input)) return input;
            input = input.Replace(Environment.NewLine, "");
            return input.Replace(" ", "");
        }

        private static void ConvertNodePropertyValuesToNodeRevision()
        {
            Console.WriteLine("\n\nConversion des NodePropertyValue en NodeRevision en cours...");

            NodePropertyValueConverter.ConvertAllNodePropertyValueToNodeRevisions();

            Console.Write("\nOpération complétée avec succès.");
        }

        private static void ConvertNodeRevisionToNewNodeRevision()
        {
            Console.WriteLine("\n\nConversion des NodeRevision...");

            NodePropertyValueConverter.ConvertNodeRevisionToNewNodeRevision();

            Console.Write("\nOpération complétée avec succès.");
        }

        private static void ConvertNodeRevisionAllInOneToNodeRevisionWithCulture()
        {
            Console.WriteLine("\n\nConversion des NodeRevision...");

            NodePropertyValueConverter.ConvertNodeRevisionAllInOneToNodeRevisionWithCulture();

            Console.Write("\nOpération complétée avec succès.");
        }

        private static void DeserializeProfileNodes()
        {
            Console.WriteLine("\n\nDésérialisation des noeuds de profil en cours...");

            var profiles = NodeManager.GetNodesByType<ProfileNode>(false);

            foreach (var profileNode in profiles)
            {
                profileNode.DeserializeProfileNodeProperties();
                profileNode.Status = EntityStates.Dirty;
                NodeManager.SaveNode(profileNode);
            }

            RecycleGeneratedTables(new[] { NodeTypeManager.GetNodeType(MedianamikTypes.MedianamikProfile) }, 1);
        }

        private static void GenerateDALClientCode()
        {
            var urls = new ObjectFactory<IUrlDictionary>().Get();

            Console.WriteLine("\n\nGénération de la DAL en cours...");

            var result = new CodeService()
                .GenerateClientCode(GetOuputPath());

            ShowErrors(result);
        }

        private static string GetOuputPath()
        {
            return Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) +
                   Config.CodeGeneration.OutputPath.Replace("/", "\\");
        }

        private static void GenerateMyProfile()
        {
            Console.WriteLine("\n\nGénération de la classe MyProfile...");

            var result = new CodeService()
                .GenerateMyProfileClass(System.IO.Path
                .GetDirectoryName(System.Reflection.Assembly
                .GetEntryAssembly().Location));

            ShowErrors(result);
        }

        private static string GetMyProfileClassPath()
        {
            return ((ProfileSection)ConfigurationManager
                .GetSection("system.web/profile")).Inherits;
        }

        private static void GenerateUserProfile()
        {
            Console.WriteLine("\n\nGénération de la classe UserProfile...");

            new CodeGenerator().GenerateUserProfile(GetOuputPath());

            Console.Write("\nOpération complétée avec succès.");
        }

        private static void InstallUserManagementModule2()
        {
            Console.WriteLine("\n\nInstallation du module de gestion des membres 2...");

            using (var connection = new SqlConnection(ConfigurationManager
               .ConnectionStrings["CS"].ConnectionString))
            {
                const string updateUserProfileViewNonQuery =
                    @"IF NOT EXISTS( SELECT NULL  FROM medianamik_Node where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10')  BEGIN  INSERT INTO [dbo].[medianamik_Node]             ([NodeId]             ,[ParentNodeId]             ,[TypeId]             ,[CreatedOn]             ,[CreatedBy]             ,[ModifiedOn]             ,[ModifiedBy]             ,[Flags]             ,[IsDeleted]             ,[Path]             ,[Depth]             ,[Position]             ,[EditedOn]             ,[EditedBy])       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0'                        ,'3DAD4D08-B9BC-4603-A8DE-42A88A354B5B'             ,'2010-12-15 15:25:27.337'             ,''             ,'2011-01-05 10:27:22.230'             ,''             ,         0             ,         0             ,'.7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0.E025C80D-8861-4470-AF51-9087267C9C10.'             ,         1             ,         0             ,'2011-01-05 10:27:22.230'             ,'sa'             )  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND CultureNAme = 'fr-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('24BDC069-D7DB-4359-B074-2D8C94FDF42D'             ,'E025C80D-8861-4470-AF51-9087267C9C10'             ,         1             ,'2010-12-15 15:25:27.353'             ,'fr-CA')  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND CultureNAme = 'en-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('1CBB0FA3-5830-4411-9A8E-372040484FAE'             ,'E025C80D-8861-4470-AF51-9087267C9C10'             ,         1             ,'2010-12-15 15:25:27.353'             ,'en-CA')  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '60C0AA24-C355-4722-ACAA-21D363351479' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'60C0AA24-C355-4722-ACAA-21D363351479'             ,NULL                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = 'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C'             ,NULL                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '7213C44C-BBC7-4095-AE52-0DE37E7276C7' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'7213C44C-BBC7-4095-AE52-0DE37E7276C7'             ,'False'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9'             ,'membership/views/groupselector.aspx'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = 'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF'             ,'True'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '29571C7C-3B7A-4576-8BB0-F2EAF8413D20' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'29571C7C-3B7A-4576-8BB0-F2EAF8413D20'             ,'False'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'fr-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'Sélection d''un groupe'                       ,null             ,'fr-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'E025C80D-8861-4470-AF51-9087267C9C10' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'en-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('E025C80D-8861-4470-AF51-9087267C9C10'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'Group Selection'                       ,null             ,'en-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL  FROM medianamik_Node where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA')  BEGIN  INSERT INTO [dbo].[medianamik_Node]             ([NodeId]             ,[ParentNodeId]             ,[TypeId]             ,[CreatedOn]             ,[CreatedBy]             ,[ModifiedOn]             ,[ModifiedBy]             ,[Flags]             ,[IsDeleted]             ,[Path]             ,[Depth]             ,[Position]             ,[EditedOn]             ,[EditedBy])       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0'                        ,'3DAD4D08-B9BC-4603-A8DE-42A88A354B5B'             ,'2010-12-13 15:04:43.493'             ,''             ,'2010-12-13 15:04:43.493'             ,''             ,         0             ,         0             ,'.7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0.4C0673A8-0B7B-45C7-B492-BA80B52D84FA.'             ,         1             ,         0             ,'2010-12-13 15:04:43.493'             ,'sa'             )  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND CultureNAme = 'en-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('BD2DB0BE-CD1E-41EA-9636-5AB8BC412CEC'             ,'4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,         1             ,'2010-12-13 15:04:43.497'             ,'en-CA')  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND CultureNAme = 'fr-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('DE16A73C-B989-44F5-A470-A3E24D97413E'             ,'4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,         1             ,'2010-12-13 15:04:43.497'             ,'fr-CA')  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '60C0AA24-C355-4722-ACAA-21D363351479' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'60C0AA24-C355-4722-ACAA-21D363351479'             ,'52e9b12c-7e90-4f91-9117-51b484e277b0'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = 'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C'             ,'802e6ddd-403a-41cc-954d-900f5530cc3f'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '7213C44C-BBC7-4095-AE52-0DE37E7276C7' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'7213C44C-BBC7-4095-AE52-0DE37E7276C7'             ,'True'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9'             ,'views/useredit.aspx'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = 'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF'             ,'True'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '29571C7C-3B7A-4576-8BB0-F2EAF8413D20' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'29571C7C-3B7A-4576-8BB0-F2EAF8413D20'             ,'False'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'fr-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'Edition d''un usager'                       ,null             ,'fr-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '4C0673A8-0B7B-45C7-B492-BA80B52D84FA' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'en-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('4C0673A8-0B7B-45C7-B492-BA80B52D84FA'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'User Edition'                       ,null             ,'en-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL  FROM medianamik_Node where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB')  BEGIN  INSERT INTO [dbo].[medianamik_Node]             ([NodeId]             ,[ParentNodeId]             ,[TypeId]             ,[CreatedOn]             ,[CreatedBy]             ,[ModifiedOn]             ,[ModifiedBy]             ,[Flags]             ,[IsDeleted]             ,[Path]             ,[Depth]             ,[Position]             ,[EditedOn]             ,[EditedBy])       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0'                        ,'3DAD4D08-B9BC-4603-A8DE-42A88A354B5B'             ,'2010-12-13 11:09:40.670'             ,''             ,'2011-01-04 16:27:41.547'             ,''             ,         0             ,         0             ,'.7A6A4803-1D66-40F5-8DAB-76AFDAE93CF0.AC8B3165-2D04-4183-96B5-03DC85C16DAB.'             ,         1             ,         0             ,'2011-01-04 16:27:41.543'             ,'sa'             )  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND CultureNAme = 'fr-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('DD57C60D-B2C4-47FB-A0A8-461FF7F7ACC3'             ,'AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,         1             ,'2010-12-13 11:09:40.673'             ,'fr-CA')  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND CultureNAme = 'en-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('C192E754-8A3E-4588-94F1-D574312FE5F5'             ,'AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,         1             ,'2010-12-13 11:09:40.673'             ,'en-CA')  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '60C0AA24-C355-4722-ACAA-21D363351479' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'60C0AA24-C355-4722-ACAA-21D363351479'             ,'52e9b12c-7e90-4f91-9117-51b484e277b0'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = 'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'A5F1D87F-3086-4CEA-A983-A09D4FE9FC4C'             ,'802e6ddd-403a-41cc-954d-900f5530cc3f'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '7213C44C-BBC7-4095-AE52-0DE37E7276C7' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'7213C44C-BBC7-4095-AE52-0DE37E7276C7'             ,'False'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'47096ACE-4C51-4C8F-BAE2-15A6FD90F6E9'             ,'views/userlist.aspx'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = 'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'A9D96D60-4E0D-4EF6-831C-AAD02A1D2BCF'             ,'True'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '29571C7C-3B7A-4576-8BB0-F2EAF8413D20' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'29571C7C-3B7A-4576-8BB0-F2EAF8413D20'             ,'True'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'fr-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'Gestion des utilisateurs'                       ,null             ,'fr-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = 'AC8B3165-2D04-4183-96B5-03DC85C16DAB' AND PropertyId = '18232ABC-5DD8-4AE5-947A-16F3AF3A8715' AND CultureName = 'en-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('AC8B3165-2D04-4183-96B5-03DC85C16DAB'             ,'18232ABC-5DD8-4AE5-947A-16F3AF3A8715'             ,'User Management'                       ,null             ,'en-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL  FROM medianamik_Node where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F')  BEGIN  INSERT INTO [dbo].[medianamik_Node]             ([NodeId]             ,[ParentNodeId]             ,[TypeId]             ,[CreatedOn]             ,[CreatedBy]             ,[ModifiedOn]             ,[ModifiedBy]             ,[Flags]             ,[IsDeleted]             ,[Path]             ,[Depth]             ,[Position]             ,[EditedOn]             ,[EditedBy])       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,NULL                        ,'627E47FC-6C91-444F-B3A6-79B1F687EF9A'             ,'2010-12-13 11:10:26.013'             ,''             ,'2010-12-13 11:10:55.280'             ,''             ,         0             ,         0             ,'.802E6DDD-403A-41CC-954D-900F5530CC3F.'             ,         0             ,         0             ,'2010-12-13 11:10:55.280'             ,'sa'             )  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND CultureNAme = 'en-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('DF6D0C2B-70C7-4C05-B9F8-0F088B0CC2C6'             ,'802E6DDD-403A-41CC-954D-900F5530CC3F'             ,         1             ,'2010-12-13 11:10:26.013'             ,'en-CA')  END
                    IF NOT EXISTS(SELECT NULL FROM Medianamik_NodeInstance WHERE NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND CultureNAme = 'fr-CA')  BEGIN  INSERT INTO [dbo].[medianamik_NodeInstance]             ([NodeInstanceId]             ,[NodeId]             ,[IsActive]             ,[CreatedOn]             ,[CultureName])       VALUES             ('E981873B-C974-49DA-A138-6F032E760B48'             ,'802E6DDD-403A-41CC-954D-900F5530CC3F'             ,         1             ,'2010-12-13 11:10:26.013'             ,'fr-CA')  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = '5DEC52FD-25C3-4AB3-AFC7-6E1E38437FF1' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'5DEC52FD-25C3-4AB3-AFC7-6E1E38437FF1'             ,NULL                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = '19AE84AF-386F-41D9-ACD3-82EBB313A28F' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'19AE84AF-386F-41D9-ACD3-82EBB313A28F'             ,'False'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = '12179708-3E1B-4E30-A654-B762E9E3159C' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'12179708-3E1B-4E30-A654-B762E9E3159C'             ,'membership'                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = 'B13C9212-65B3-491B-8DC7-C2E775A6D669' AND CultureName = '' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'B13C9212-65B3-491B-8DC7-C2E775A6D669'             ,''                       ,null             ,''             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = '277B7D42-8EC5-400F-8FF6-6E832A36F18C' AND CultureName = 'fr-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'277B7D42-8EC5-400F-8FF6-6E832A36F18C'             ,'Gestion des usagers'                       ,null             ,'fr-CA'             ,null             )  END
                    IF NOT EXISTS( SELECT NULL FROM medianamik_NodePropertyValue where NodeId = '802E6DDD-403A-41CC-954D-900F5530CC3F' AND PropertyId = '277B7D42-8EC5-400F-8FF6-6E832A36F18C' AND CultureName = 'en-CA' AND Revision IS NULL)  BEGIN  INSERT INTO [dbo].[medianamik_NodePropertyValue]             ([NodeId]             ,[PropertyId]             ,[Value]             ,[Revision]             ,[CultureName]             ,[EndRevision]             )       VALUES             ('802E6DDD-403A-41CC-954D-900F5530CC3F'             ,'277B7D42-8EC5-400F-8FF6-6E832A36F18C'             ,'User Management'                       ,null             ,'en-CA'             ,null             )  END
                    delete from medianamik_Node where nodeid = 'a3845877-fdb1-48fa-9c3a-f70fe46394ca'
                    delete from medianamik_Node where nodeid = '22b9493c-ee01-4980-a274-335c57b1ecef'
                    update medianamik_type set isgenerated = 1 where typeid = '45C90CDA-E48D-4F9E-A5A4-1C398B9DD5F5'
                    update medianamik_type set isversioned = 0 where typeid = '45C90CDA-E48D-4F9E-A5A4-1C398B9DD5F5'
                    update medianamik_type set extendedproperties = '<ExtendedProperties><ClientTemplatePaths /><Icon>/Medianamik/images/NodeTypeIcons/Ico_Carriere.png</Icon></ExtendedProperties>' where typeid = '45C90CDA-E48D-4F9E-A5A4-1C398B9DD5F5'";

                var command = new SqlCommand(updateUserProfileViewNonQuery, connection);
                command.Connection.Open();
                command.ExecuteNonQuery();

                RegenerateUserProfileView();
            }

            new CodeGenerator().GenerateUserProfile(GetOuputPath());

            Console.Write("\nOpération complétée avec succès.");
        }

        private static void RegenerateUserProfileView()
        {
            var codeService = new CodeService();
            codeService.RegenerateUserProfileView();
        }

        private static void ShowErrors(CodeGenerationResult result)
        {
            if (result.HasErrors)
            {
                Console.Write("\nUne erreur est survenue, veuillez consulter le fichier de log.");
            }
            else
            {
                Console.Write("\nOpération complétée avec succès.");
            }
        }

        private static void RecycleGeneratedTables(IEnumerable<NodeType> allTypes, int allTypesCount)
        {
            var recycledTypes = 0;

            var stopWatch = new Stopwatch();
            stopWatch.Start();

            Console.WriteLine("\n\nAppuyez sur CTRL + C pour annuler.");

            Console.WriteLine("\n\nRégénération des tables en cours...");

            var codeService = new CodeService();

            _canceled = false;

            foreach (var type in allTypes)
            {
                if (_canceled)
                    break;

                var currentType = type;

                Console.WriteLine("\t- Régénération du type " + type.Name + "...");
                codeService.GenerateTableAndView(currentType);

                Console.WriteLine("\t- Insertion des noeuds de type " + type.Name + "...");
                codeService.FillTable(currentType);

                recycledTypes++;

                if (_canceled)
                    break;
            }

            foreach (var nodeTypeInterface in NodeTypeManager.GetAllNodeTypeInterfaces())
            {
                codeService.GenerateView(nodeTypeInterface);
            }

            RegenerateUserProfileView();

            stopWatch.Stop();

            Console.WriteLine("\n\nNombre de tables recyclées : " + recycledTypes +
                         "/" + allTypesCount + " en " + stopWatch.Elapsed);
        }

        private static string ConfirmAction(string message, Action action)
        {
            Console.Write("\n\n" + message);

            if (Console.ReadKey().KeyChar.ToString().Equals("o", StringComparison.OrdinalIgnoreCase))
            {
                action.Invoke();
            }

            return "";
        }

        private static void CleanDatabase()
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            Console.WriteLine("\n\nNettoyage de la BD en cours...");

            var codeService = new CodeService();


            codeService.CleanUpDatabase();

            stopWatch.Stop();

            Console.WriteLine("\nNettoyage de la BD terminé" + " en " + stopWatch.Elapsed);
        }

        private static void UpdateMedianamik()
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            Console.WriteLine("\n\nApplication des mises-à-jour en cours...");

            var changes = ConfigManager.GetSchemaChangesMerged()
                .Where(c => !c.DateApplied.HasValue);

            foreach (var change in changes)
            {
                ConfigManager.ApplySchemaChange(change);
            }

            stopWatch.Stop();

            Console.WriteLine("\nMises-à-jour appliquées" + " en " + stopWatch.Elapsed);
        }

        private static string DisplayOperations()
        {
            Console.WriteLine("\n\nVeuillez choisir l'une des opérations suivantes : ");

            Console.Write("\n\t- Appuyez sur 1 pour recycler les tables générées.");
            Console.Write("\n\t- Appuyez sur 2 pour générer la DAL.");
            Console.Write("\n\t- Appuyez sur 3 pour nettoyer la BD.");
            Console.Write("\n\t- Appuyez sur 4 pour appliquer les mises-à-jour.");
            Console.Write("\n\t- Appuyez sur 5 pour générer la classe MyProfile.");
            Console.Write("\n\t- Appuyez sur 6 pour désérialiser les noeuds de type MedianamikProfile.");
            Console.Write("\n\t- Appuyez sur 7 pour installer le module de gestion des membres 2.");
            Console.Write("\n\t- Appuyez sur 8 pour générer la classe UserProfile.");
            Console.Write("\n\t- Appuyez sur 9 pour passer à la version 2.3.1.x ou plus.");
            Console.Write("\n\t- Appuyez sur 10 pour passer à la version 2.4.x.x ou plus.");
            Console.Write("\n\t- Appuyez sur 11 pour ConvertNodeRevisionAllInOneToNodeRevisionWithCulture.");
            Console.Write("\n\t- Appuyez sur 12 pour comparer ce site à un autre.");
            Console.Write("\n\t- Appuyez sur 13 pour regénérer la vue UserProfile.");
            Console.Write("\n\t- Appuyez sur 14 pour quitter.");
            Console.Write("\n\nAppuyez sur le nombre correspondent à l'opération à effectuer : ");
            return Console.ReadLine();
        }

        static void CancelRecyling(object sender, ConsoleCancelEventArgs e)
        {
            e.Cancel = true;
            _canceled = true;
        }
    }

    public class RepositoriesRegistry : Registry
    {
        public RepositoriesRegistry()
        {


            ForRequestedType<ICurrentNodeIdRetriever>()
                 .TheDefaultIsConcreteType<CurrentNodeIdRetriever>();

            ForRequestedType(typeof(ICacheService<>))
                .TheDefaultIsConcreteType(typeof(CacheService<>));

            ForRequestedType<ICurrentNodeIdRetriever>()
                .TheDefaultIsConcreteType<CurrentNodeIdRetriever>();

            ForRequestedType<ICultureService>()
                .TheDefaultIsConcreteType<CultureService>();

            ForRequestedType<IContentStateService>()
                .TheDefaultIsConcreteType<ContentStateService>();

            ForRequestedType<INodeMapper>()
                .TheDefaultIsConcreteType<NodeMapper>();


            ForRequestedType<IMedianamikRepository<IMedianamikDTOWithName>>()
               .TheDefaultIsConcreteType<MedianamikDTOWithNameRepository>();

            ForRequestedType<IBaseTypeRepository>()
                .TheDefaultIsConcreteType<BaseTypeRepository>();

            ForRequestedType<INodeRepository>()
                .TheDefaultIsConcreteType<NodeRepository>();

            ForRequestedType<INodeTypeRepository>()
                .TheDefaultIsConcreteType<NodeTypeRepository>();

            ForRequestedType<IUrlRepository>()
                .TheDefaultIsConcreteType<UrlRepository>();

            ForRequestedType<IMedianamikRepository<BaseWebType>>()
                .TheDefaultIsConcreteType<BaseWebTypeRepository>();
        }
    }
}